﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

namespace SAP
{
    public partial class P_WSCA : System.Web.UI.Page
    {

        private static string GeneralID = "";
        private static string dbType;

        private static int WSCID = -1;
        private static string VIN = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                dbType = Session[VSM.Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? VSM.Utils.AppConstants.VSM : VSM.Utils.AppConstants.DEALER;
                GeneralID = Request.QueryString["GeneralID"] == null ? "" : Request.QueryString["GeneralID"];
                VIN = Request.QueryString["VIN"] == null ? "" : Request.QueryString["VIN"];
                hf_GeneralID.Value = GeneralID.ToString();
                 loadDropdownList();

                loadWSC();
               
                if (WSCID == -1)
                {
                    loadDefaultNew(VIN);
                }
                //editItemUpdatePanel.Update();
            }
        }

        private void loadDropdownList() {
            DataTable tbType = new DataTable();
            tbType.Columns.Add("Code");
            tbType.Columns.Add("Name");

            tbType.Rows.Add("W", "General");
            tbType.Rows.Add("E", "Policy Claim");
            tbType.Rows.Add("P", "Part Warranty");
            tbType.Rows.Add("X", "Other");

            ddl_T.DataSource = tbType;
            ddl_T.DataTextField = "Name";
            ddl_T.DataValueField = "Code";
            ddl_T.DataBind();

            DataTable tbDiv = new DataTable();
            tbDiv.Columns.Add("Code");
            tbDiv.Columns.Add("Name");
            tbDiv.Rows.Add("S", "Standard");
            tbDiv.Rows.Add("T", "Transient Owner");
            tbDiv.Rows.Add("X", "Other");

            ddl_DIV.DataSource = tbDiv;
            ddl_DIV.DataTextField = "Name";
            ddl_DIV.DataValueField = "Code";
            ddl_DIV.DataBind();

            Services sv = new Services();
            ddl_A.DataSource = sv.ExecuteQuery("VSM", "select Code, Code + '-' + Name as Name, [Type] from U_RefCode where [Type] = 'A'").Tables[0];
            ddl_A.DataValueField = "Code";
            ddl_A.DataTextField = "Name";
            ddl_A.DataBind();

            ddl_B.DataSource = sv.ExecuteQuery("VSM", "select Code, Code + '-' + Name as Name, [Type] from U_RefCode where [Type] = 'B'").Tables[0];
            ddl_B.DataValueField = "Code";
            ddl_B.DataTextField = "Name";
            ddl_B.DataBind();

            ddl_C.DataSource = sv.ExecuteQuery("VSM", "select Code, Code + '-' + Name as Name, [Type] from U_RefCode where [Type] = 'C'").Tables[0];
            ddl_C.DataValueField = "Code";
            ddl_C.DataTextField = "Name";
            ddl_C.DataBind();
        }
        private void loadWSC()
        {
            string sql = "SELECT [WSCID],gs.[GeneralID],wsc.[RegistrationNum],wsc.[DisCode],wsc.[DisName],wsc.[DealerCode],wsc.[DealerName] ";
            sql += " ,wsc.[SeqNo],[InvoiceDate],wsc.[S],wsc.[ID],wsc.[T],wsc.[DIV],[ConditionCode],[A],[B],[C],gs.[CustomerName],gs.[VIN],[FailureDate],[KD], ";
            sql += " [SoldDate],[HourMeter],[Manu],[RefCode],[M],[COM],[RatioL],[RatioP],[FCT],[Remarks],wsc.[Status], gs.Model, EngineNumber,  ";
            sql += "  ServiceDate, Odometer ";
            sql += "  FROM [U_WSC] wsc join U_GeneralService gs on wsc.GeneralID = gs.GeneralID ";
            sql += "  where wsc.GeneralID = " + GeneralID.ToString();

            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                WSCID = Int32.Parse(dr["WSCID"].ToString());

                txtDate.Text = FormatDate(dr["ServiceDate"].ToString());
                txt_Odometer.Text = dr["Odometer"].ToString();

                txt_RegistrationNum.Text = dr["RegistrationNum"].ToString();
                txt_DistCode.Text = dr["DisCode"].ToString();
                txt_DistName.Text = dr["DisName"].ToString();
                txt_DealerCode.Text = dr["DealerCode"].ToString();
                txt_DealerName.Text = dr["DealerName"].ToString();
                txt_SeqNo.Text = dr["SeqNo"].ToString();
                txt_InvoiceDate.Text = FormatDate(dr["InvoiceDate"].ToString());
                txt_S.Text = dr["S"].ToString();

                txt_ID.Text = dr["ID"].ToString();

                if (ddl_T.Items.FindByValue(dr["T"].ToString()) != null)
                    ddl_T.Items.FindByValue(dr["T"].ToString()).Selected = true;

                if (ddl_DIV.Items.FindByValue(dr["DIV"].ToString()) != null)
                    ddl_DIV.Items.FindByValue(dr["DIV"].ToString()).Selected = true;

                txt_Model.Text = dr["Model"].ToString();
                txt_EngineNum.Text = dr["EngineNumber"].ToString();

                txt_ConditionCode.Text = dr["ConditionCode"].ToString();

                if (ddl_A.Items.FindByValue(dr["A"].ToString()) != null)
                    ddl_A.Items.FindByValue(dr["A"].ToString()).Selected = true;
                if (ddl_B.Items.FindByValue(dr["B"].ToString()) != null)
                    ddl_B.Items.FindByValue(dr["B"].ToString()).Selected = true;
                if (ddl_C.Items.FindByValue(dr["C"].ToString()) != null)
                    ddl_C.Items.FindByValue(dr["C"].ToString()).Selected = true;

                txt_CusName.Text = dr["CustomerName"].ToString();
                txt_VIN.Text = dr["VIN"].ToString();

                txt_FailureDate.Text = FormatDate(dr["FailureDate"].ToString());

                chk_KD.Checked = dr["KD"].ToString() == "1" ? true : false;

                txt_SoldDate.Text = FormatDate(dr["SoldDate"].ToString());

                txt_HourMeter.Text = dr["HourMeter"].ToString();
                txt_Manu.Text = dr["Manu"].ToString();
                txt_RefCode.Text = dr["RefCode"].ToString();
                txt_M.Text = dr["M"].ToString();
                txt_COM.Text = dr["COM"].ToString();
                txt_RatioL.Text = dr["RatioL"].ToString();
                txt_RatioP.Text = dr["RatioP"].ToString();
                txt_FCT.Text = dr["FCT"].ToString();
                txt_Notice.Text = dr["Remarks"].ToString();
            }
        }

        private string FormatDate(string dateIn)
        {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");

        }

        private void loadDefaultNew(string VIN)
        {
            //get dealer Name
            Services sv = new Services();
            string sqlDealer = "select CardCode, CardName from OCRD where CardCode = '" + Session[VSM.Utils.AppConstants.ID_Dealer] + "'";
            DataSet dsDealer = sv.ExecuteQuery("VSM", sqlDealer);
            if (dsDealer.Tables[0].Rows.Count > 0)
            {
                txt_DealerCode.Text = dsDealer.Tables[0].Rows[0]["CardCode"].ToString();
                txt_DealerName.Text = dsDealer.Tables[0].Rows[0]["CardName"].ToString();
            }

            string sql = " select inv.DocDate, rn.DistNumber as VIN, rn.Notes as EngineNo, ms.Name as ModelName, ";
            sql += " cg.RegistrationNumber, inv.CardCode, inv.CardName ";
            sql += " from OINV inv join INV1 inv1 on inv.DocEntry = inv1.BaseEntry ";
            sql += " join  OSRN rn on inv1.ItemCode = rn.ItemCode ";
            sql += " join OITM it on it.ItemCode = inv1.ItemCode ";
            sql += " join [@ModelSales] ms on ms.Code = it.U_ModelSales ";
            sql += " left join U_CustomerRegis cg on cg.VIN = rn.DistNumber ";
            sql += " where rn.DistNumber = '" + VIN + "'";

            DataSet dsInfo = sv.ExecuteQuery("VSM", sql);

            if (dsInfo.Tables[0].Rows.Count > 0)
            {
                txt_RegistrationNum.Text = dsInfo.Tables[0].Rows[0]["RegistrationNumber"].ToString();
                txt_InvoiceDate.Text = FormatDate(dsInfo.Tables[0].Rows[0]["DocDate"].ToString());
                txt_CusName.Text = dsInfo.Tables[0].Rows[0]["CardName"].ToString();
                txt_VIN.Text = dsInfo.Tables[0].Rows[0]["VIN"].ToString();
                txt_Model.Text = dsInfo.Tables[0].Rows[0]["ModelName"].ToString();
                txt_EngineNum.Text = dsInfo.Tables[0].Rows[0]["EngineNo"].ToString();
            }

            DateTime currDate = DateTime.Now;
            string sqlSeqNo = "select RIGHT('000' + cast((count(GeneralID)) as nvarchar(10)), 4) as NewSeqNo from U_GeneralService ";
            sqlSeqNo += " where JobKind = '004' and DealerCode = '" + Session[VSM.Utils.AppConstants.ID_Dealer] + "' and year(ServiceDate) = " + currDate.Year;
            DataSet dsSeq = sv.ExecuteQuery("DEALER", sqlSeqNo);
            if (dsSeq.Tables[0].Rows.Count > 0)
            {
                txt_SeqNo.Text = dsSeq.Tables[0].Rows[0]["NewSeqNo"].ToString();
            }
            //string sqlSeq = "select RIGHT('0000' + cast((isnull(max(SeqNo), 0) + 1)as nvarchar(10)), 4) NextNumber from U_WSC where DealerCode = '" + Session[VSM.Utils.AppConstants.ID_Dealer] + "'";
            //DataSet dsSeq = sv.ExecuteQuery("DEALER", sqlSeq);
            //txt_SeqNo.Text = dsSeq.Tables[0].Rows[0]["NextNumber"].ToString();

            string sqlOdo = "select Odometer, ServiceDate from U_GeneralService where GeneralID = " + GeneralID.ToString();
            DataSet dsOdo = sv.ExecuteQuery("DEALER", sqlOdo);
            if (dsOdo.Tables[0].Rows.Count > 0)
            {
                txt_Odometer.Text = dsOdo.Tables[0].Rows[0]["Odometer"].ToString();
                txtDate.Text = FormatDate(dsOdo.Tables[0].Rows[0]["ServiceDate"].ToString());
            }
        }
        


        protected void btn_Save_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("GeneralID");
            dt.Columns.Add("RegistrationNum");
            dt.Columns.Add("DisCode");
            dt.Columns.Add("DisName");
            dt.Columns.Add("DealerCode");
            dt.Columns.Add("DealerName");
            dt.Columns.Add("SeqNo");
            dt.Columns.Add("InvoiceDate");
            dt.Columns.Add("S");
            dt.Columns.Add("ID");
            dt.Columns.Add("T");
            dt.Columns.Add("DIV");
            dt.Columns.Add("ConditionCode");
            dt.Columns.Add("A");
            dt.Columns.Add("B");
            dt.Columns.Add("C");
            dt.Columns.Add("CustomerName");
            dt.Columns.Add("VIN");
            dt.Columns.Add("FailureDate");
            dt.Columns.Add("KD");
            dt.Columns.Add("SoldDate");
            dt.Columns.Add("HourMeter");
            dt.Columns.Add("Manu");
            dt.Columns.Add("RefCode");
            dt.Columns.Add("M");
            dt.Columns.Add("COM");
            dt.Columns.Add("RatioL");
            dt.Columns.Add("RatioP");
            dt.Columns.Add("FCT");
            dt.Columns.Add("Remarks");
            dt.Columns.Add("Status");
            dt.Columns.Add("WSCID");
            dt.Columns.Add("Model");
            dt.Columns.Add("EngineNumber");

            DataRow dr = dt.NewRow();
            dr["GeneralID"] = GeneralID;
            dr["RegistrationNum"] = txt_RegistrationNum.Text;
            dr["DisCode"] = txt_DistCode.Text;
            dr["DisName"] = txt_DistName.Text;
            dr["DealerCode"] = txt_DealerCode.Text;
            dr["DealerName"] = txt_DealerName.Text;
            dr["SeqNo"] = txt_SeqNo.Text;

            if (txt_InvoiceDate.Text.Trim() == "")
                dr["InvoiceDate"] = DBNull.Value;
            else
                dr["InvoiceDate"] = VSM.Utils.AppConstants.ConvertToDate(txt_InvoiceDate.Text.Trim());

            dr["S"] = txt_S.Text;

            dr["ID"] = txt_ID.Text;
            dr["T"] = ddl_T.SelectedValue;
            dr["DIV"] = ddl_DIV.SelectedValue;

            dr["ConditionCode"] = txt_ConditionCode.Text;
            dr["A"] = ddl_A.SelectedValue;
            dr["B"] = ddl_B.SelectedValue;
            dr["C"] = ddl_C.SelectedValue;
            dr["CustomerName"] = txt_CusName.Text;
            dr["VIN"] = txt_VIN.Text;

            if (txt_FailureDate.Text.Trim() == "")
                dr["FailureDate"] = DBNull.Value;
            else
                dr["FailureDate"] = VSM.Utils.AppConstants.ConvertToDate(txt_FailureDate.Text.Trim());

            dr["KD"] = chk_KD.Checked == true ? 1 : 0;

            if (txt_SoldDate.Text.Trim() == "")
                dr["SoldDate"] = DBNull.Value;
            else
                dr["SoldDate"] = VSM.Utils.AppConstants.ConvertToDate(txt_SoldDate.Text.Trim());

            dr["HourMeter"] = txt_HourMeter.Text;
            dr["Manu"] = txt_Manu.Text;
            dr["RefCode"] = txt_RefCode.Text;
            dr["M"] = txt_M.Text;
            dr["COM"] = txt_COM.Text;
            dr["RatioL"] = txt_RatioL.Text;
            dr["RatioP"] = txt_RatioP.Text;
            dr["FCT"] = txt_FCT.Text;
            dr["Remarks"] = txt_Notice.Text;
            dr["Status"] = 0;
            dr["WSCID"] = WSCID;

            dr["Model"] = txt_Model.Text;
            dr["EngineNumber"] = txt_EngineNum.Text;

            dt.Rows.Add(dr);

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            Services sv = new Services();
            if (WSCID == -1)
            {
                WSCID = sv.InsertWSC(dbType, ds);
                if (WSCID != -1)
                {
                    lb_Message.Text = "[Add New] Operation complete.";
                }
                else
                    lb_Message.Text = "[Add New] Operation failure.";
            }
            else
            {
                int count = sv.UpdateWSC(dbType, ds);
                if (count != -1)
                    lb_Message.Text = "[Update] Operation complete.";
                else
                    lb_Message.Text = "[Update] Operation failure.";
            }
        }
    }
}